package com.compass.doctor.ui.patient.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.compass.doctor.R
import com.compass.doctor.base.BaseVBFragment
import com.compass.doctor.callback.OnCustomButtonClick
import com.compass.doctor.databinding.FragmentPatientBinding
import com.compass.doctor.databinding.LayoutPatientHeadBinding
import com.compass.doctor.ui.patient.MassMessagingActivity
import com.compass.doctor.ui.patient.NewPatientActivity
import com.compass.doctor.ui.patient.PatientChatActivity
import com.compass.doctor.ui.patient.PatientDetailsActivity
import com.compass.doctor.ui.patient.PractitionerToPatientChatActivity
import com.compass.doctor.ui.patient.adapter.PatientAdapter
import com.compass.doctor.ui.patient.adapter.PatientMenuTagAdapter
import com.compass.doctor.ui.patient.viewmodel.PatientViewModel
import com.compass.framework.constant.CLINICAL_RECEPTION
import com.compass.framework.constant.REFRESH_PATIENT
import com.compass.framework.ext.gone
import com.compass.framework.ext.onClick
import com.compass.framework.ext.textChangeFlow
import com.compass.framework.ext.visible
import com.compass.framework.manager.UserInfoManager
import com.compass.framework.model.Tag
import com.compass.framework.utils.LiveDataBus
import com.compass.framework.utils.getColorDrawable
import com.compass.framework.utils.getDrawableResource
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexWrap
import com.google.android.flexbox.FlexboxLayoutManager
import com.google.android.flexbox.JustifyContent
import com.netease.yunxin.kit.corekit.im.model.UserInfo
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshListener
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach


/**
 *患者列表
 */
class PatientFragment : BaseVBFragment<FragmentPatientBinding>(), OnRefreshListener {

    private lateinit var mAdapter: PatientAdapter
    private lateinit var patientTagAdapter: PatientMenuTagAdapter

    private var tags: MutableList<Tag> = mutableListOf()
    private val patientViewModel: PatientViewModel by viewModels()
    private var isLinear: Boolean = true//初始化线性
    private var headIsAdd: Boolean = false//是否添加了
    private var key: String = ""
    private var tagString: String = ""
    private var tagsId: MutableList<String> = mutableListOf()
    private lateinit var patientHeadBinding: LayoutPatientHeadBinding
    override fun initView(view: View, savedInstanceState: Bundle?) {
        patientHeadBinding = LayoutPatientHeadBinding.inflate(LayoutInflater.from(requireContext()))
        mAdapter = PatientAdapter(0)
        patientTagAdapter = PatientMenuTagAdapter()
        initTitleBarRight()
        initRecyclerView()
        initSearch()

    }

    private fun initSearch() {
//        mBinding?.edtDiagnosis?.textChangeFlow()
//            ?.distinctUntilChanged()
//            ?.debounce(500)
//            ?.flowOn(Dispatchers.IO)
//            ?.onEach {
//                //这里走查询接口
//                key = mBinding?.edtDiagnosis?.text.toString()
//                patientViewModel.getMyPatientList(key = key, tags = tagString)
//            }
//            ?.launchIn(lifecycleScope)

        mBinding?.edtDiagnosis?.addTextChangedListener {
            if (it.toString().isEmpty()) {
                key = ""
                patientViewModel.getMyPatientList(key = key, tags = tagString)
            }
        }

        mBinding?.edtDiagnosis?.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                key = mBinding?.edtDiagnosis?.text.toString()
                patientViewModel.getMyPatientList(key = key, tags = tagString)
            }
            false
        }

        mBinding?.refreshLayout?.apply {
            setEnableRefresh(true)
            setEnableLoadMore(false)
            setOnRefreshListener(this@PatientFragment)
        }
    }

    private fun initTitleBarRight() {
        mBinding?.tvTitleBar?.getRightLayout()?.onClick {
            //群发消息
            MassMessagingActivity.start(requireContext())
//            val context = context
//            val memberLimit = ConversationUIConstant.MAX_TEAM_MEMBER
//            val contentListPopView = CustomListPopView.Builder(context)
//                .addItem(PopItemFactory.getAddFriendItem(context))
//                .addItem(PopItemFactory.getDivideLineItem(context))
//                .addItem(PopItemFactory.getSendMessageItem(context, memberLimit))
//                .enableShadow(true)
//                .backgroundRes(R.drawable.conversation_view_pop_bg)
//                .build()
//            contentListPopView.showAsDropDown(
//                it, dpToPx(50), dpToPx(-10)
//            )
        }
    }

    override fun intListener() {
        mAdapter.onItemClickListener = { view: View, position: Int ->
            val patientInfo = mAdapter.getItem(position)
            patientInfo?.let {
                PatientDetailsActivity.start(requireContext(), patientInfo.id)
            }

        }
        mAdapter.setBottomClick(object : OnCustomButtonClick {
            override fun onButtonCallBack(position: Int, msgType: String?) {
                val patientInfo = mAdapter.getItem(position)
                patientInfo?.let {

                    if (UserInfoManager.getUserType()=="1"){
                        PatientChatActivity.start(
                            requireContext(),
                            UserInfo(it.wyyxAccId, it.name, it.avatar), it.id
                        )
                    }else{
                        PractitionerToPatientChatActivity.start(
                            requireContext(),
                            UserInfo(it.wyyxAccId, it.name, it.avatar),
                            it.id
                        )
                    }


                }
            }
        })

    }

    private fun initRecyclerView() {
        mBinding?.apply {
            rcyPatient.apply {
                layoutManager =
                    LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
                adapter = mAdapter

            }
            initRcyTag()
            patientTag.onClick {
                initRcyTag()
            }
            relPatient.onClick {
                //非线性才可点击
                initRcyTag()
            }
            patientTagAdapter.onItemClickListener = { _: View, position: Int ->
                    tags[position].id?.let {
                        tags[position].isSelect = !tags[position].isSelect
                        tagsId.clear()
                        for (tagItem in tags) {
                            if (tagItem.isSelect) tagsId.add(tagItem.title)
                        }
                        tagString = tagsId.joinToString(separator = ",")
                        patientTagAdapter.notifyDataSetChanged()
                        patientViewModel.getMyPatientList(key = key, tags = tagString)
                    }

            }
        }
    }

    private fun initHeadView() {
        if (!headIsAdd) {
            headIsAdd = true

            mAdapter.addHeadView(patientHeadBinding.root)
            patientHeadBinding.llNewPatient.onClick {
                NewPatientActivity.start(requireContext())
            }
        }

    }

    private fun initRcyTag() {
        mBinding?.rcyTab.apply {
            if (isLinear) {
                mBinding?.relPatient?.layoutParams?.height = ViewGroup.LayoutParams.WRAP_CONTENT
                mBinding?.relPatient?.background =
                    getColorDrawable(com.compass.framework.R.color.transparent)
                mBinding?.rcyTab?.background = getColorDrawable(com.compass.framework.R.color.white)
                mBinding?.rcyTab?.layoutManager =
                    LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
                isLinear = false
            } else {
                isLinear = true
                mBinding?.relPatient?.layoutParams?.height = ViewGroup.LayoutParams.MATCH_PARENT
                mBinding?.relPatient?.background =
                    getColorDrawable(com.compass.framework.R.color.transparent_background)
                mBinding?.rcyTab?.background =
                    getDrawableResource(R.drawable.bg_shape_bottom_white_10)
                val layoutFelManager = FlexboxLayoutManager(context)
                layoutFelManager.flexWrap = FlexWrap.WRAP // 按正常方向换行
                layoutFelManager.flexDirection = FlexDirection.ROW // 水平方向
                layoutFelManager.justifyContent = JustifyContent.FLEX_START // 左对齐
                mBinding?.rcyTab?.layoutManager = layoutFelManager
            }



            mBinding?.rcyTab?.adapter = patientTagAdapter
        }
    }


    override fun initData() {
        LiveDataBus.get().with(CLINICAL_RECEPTION, String::class.java)
            .observe(this) {
                getPatientList()
            }


        //暂时这么些后续优化
        LiveDataBus.get().with(REFRESH_PATIENT, String::class.java).observe(this) {
            patientViewModel.getMyPatientList(key = key, tags = tagString)
            patientViewModel.getPatientTag()
        }
        getPatientList()
        patientViewModel.getPatientTag()


        patientViewModel.myPatientLiveData.observe(this) { patientWarp ->

            mBinding?.refreshLayout?.finishRefresh()
            patientWarp?.let {
                patientHeadBinding.tvNewPatient.text = "新的患者(${it.newNum})"
                if (it.list.isNullOrEmpty()) {
                    mBinding?.rcyPatient?.gone()
                    mBinding?.relPatient?.gone()
                    mBinding?.emptyView?.visible()
                } else {
                    mBinding?.relPatient?.visible()
                    mBinding?.rcyPatient?.visible()
                    mBinding?.emptyView?.gone()
                    initHeadView()
                    mAdapter.setData(it.list)
                }
            } ?: kotlin.run {
                mBinding?.rcyPatient?.gone()
                mBinding?.relPatient?.gone()
                mBinding?.emptyView?.visible()
            }
        }
        patientViewModel.allTagLiveData.observe(this) {
            it?.let { tagList ->
                if (tagList.isEmpty()) tags.add(Tag(null, "暂无标签")) else tags = tagList

                patientTagAdapter.setData(tags)
            }

        }

    }


    override fun onRefresh(refreshLayout: RefreshLayout) {
        getPatientList()
    }

    private fun getPatientList(){
        patientViewModel.getMyPatientList(key = key, tags = tagString)
    }

}